package com.weilele.mvvmlib.fragment


import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.weilele.base.library.BaseBindingFragment
import com.weilele.base.library.FragmentContainerActivity
import com.weilele.delegate.mvvmViewModel
import com.weilele.mvvm.adapter.mvvmConcatAdapter
import com.weilele.mvvm.adapter.mvvmListAdapter
import com.weilele.mvvm.adapter.refreshList
import com.weilele.mvvm.base.helper.refreshPageHelper
import com.weilele.mvvm.base.livedata.LiveDataWrap
import com.weilele.mvvm.base.livedata.data
import com.weilele.mvvm.base.livedata.wrapSuccessObserver
import com.weilele.mvvmlib.databinding.FragmentMainBinding
import com.weilele.mvvmlib.model.PicBean
import com.weilele.mvvmlib.model.PicViewModel
import com.weilele.mvvmlib.sample.holder.PicHolder
import com.weilele.mvvmlib.sample.holder.SimpleTextHolder


class MainFragment : BaseBindingFragment<FragmentMainBinding>() {
    companion object {
        fun start(appCompatActivity: AppCompatActivity) {
            FragmentContainerActivity.invoke<MainFragment>(appCompatActivity)
        }
    }

    private val picAdapter = mvvmListAdapter(PicHolder::class.java, ::areSamePic, ::areSamePic)
    private val loadMoreAdapter = SimpleTextHolder.toAdapter()
    private val rcvAdapter = mvvmConcatAdapter(picAdapter, loadMoreAdapter)
    private val picViewModel by mvvmViewModel<PicViewModel>()


    private fun onScrollEnd() {
        picViewModel.getPic(false)
    }

    override fun initUi(savedInstanceState: Bundle?) {
        super.initUi(savedInstanceState)
        mBinding.root.adapter = rcvAdapter

    }

    override fun initData() {
        super.initData()
        picViewModel.getPic(true)
    }

    override fun getObserverLiveData(): List<LiveDataWrap> {
        return listOf(
            picViewModel.picPageData wrapSuccessObserver {
                it.setOnListScrollEndListener(picAdapter, ::onScrollEnd)
                picAdapter.refreshPageHelper(it)
                loadMoreAdapter.refreshList(
                    mutableListOf(
                        SimpleTextHolder.Bean(
                            if (it.hasNextPage) {
                                "正在拼命加载"
                            } else {
                                "所有数据都加载完毕"
                            }
                        )
                    )
                )
            }
        )
    }

    private fun areSamePic(old: PicBean.DataDTO?, new: PicBean.DataDTO?): Boolean {
        return old?.url == new?.url
    }
}